package com.lzymall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lzymall.common.Const;
import com.lzymall.common.ResponseCode;
import com.lzymall.common.ServiceResponse;
import com.lzymall.dao.CartMapper;
import com.lzymall.dao.CategoryMapper;
import com.lzymall.dao.ProductMapper;
import com.lzymall.pojo.Category;
import com.lzymall.pojo.Product;
import com.lzymall.service.ICategoryService;
import com.lzymall.service.IProductService;
import com.lzymall.util.DateTimeUtil;
import com.lzymall.util.PropertiesUtil;
import com.lzymall.vo.ProductDetailVo;
import com.lzymall.vo.ProductListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.rmi.ServerError;
import java.util.List;

/**
 * @Author: lizhenyao
 * @Desciption:
 */
@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ICategoryService iCategoryService;

    @Override
    public ServiceResponse saveOrUpdateProduct(Product product) {
        if (product !=null) {
            //设置图片的main
            if (StringUtils.isNotBlank(product.getSubImages())) {
                String[] subImageArray = product.getSubImages().split(",");
                if (subImageArray.length > 0) {
                    product.setMainImage(subImageArray[0]);
                }
            }

            //id判断是更新还是新增
            if (product.getId() != null){
                int rowCount = productMapper.updateByPrimaryKey(product);
                if (rowCount > 0){
                    return ServiceResponse.createBySuccess("更新产品成功");
                }
                return ServiceResponse.createBySuccess("更新产品失败");
            }else {
                int rowCount = productMapper.updateByPrimaryKey(product);
                if (rowCount > 0){
                    return ServiceResponse.createBySuccess("新增产品成功");
                }
                return ServiceResponse.createBySuccess("新增产品失败");
            }
        }
        return ServiceResponse.createByErrorMessage("新增或者更新产品失败");
    }

    @Override
    public ServiceResponse<String> setSaleStatus(Integer productId, Integer status) {
        if (productId == null || status == null) {
            return ServiceResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        int rowCount = productMapper.updateByPrimaryKeySelective(product);
        if (rowCount > 0){
            return ServiceResponse.createBySuccess("修改产品销售状态成功");
        }
        return ServiceResponse.createByErrorMessage("修改产品销售状态失败");
    }

    @Override
    public ServiceResponse<ProductDetailVo> manageProductDetail(Integer productId) {
        if (productId == null){
            return ServiceResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null){
            return ServiceResponse.createByErrorMessage("产品已经下架或者删除");
        }
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServiceResponse.createBySuccess(productDetailVo);
    }

    @Override
    public ServiceResponse<PageInfo> getProductList(Integer pageNum, int pageSize) {
        //startPage--start
        //填充自己的sql查询逻辑
        //PageHelper--收尾
        PageHelper.startPage(pageNum, pageSize);
        List<Product> list = productMapper.selectList();
        List<ProductListVo> productListVos = Lists.newArrayList();
        for (Product product: list){
            ProductListVo productListVo = assembleProductListVo(product);
            productListVos.add(productListVo);
        }
        PageInfo pageResult = new PageInfo(list);
        pageResult.setList(productListVos);
        return ServiceResponse.createBySuccess(pageResult);
    }

    @Override
    public ServiceResponse<PageInfo> searchProduct(String productName, Integer productId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        //查找逻辑
        if (StringUtils.isNotBlank(productName)){
            productName = new StringBuilder().append("%").append(productName).append("%").toString();
        }
        List<Product> products = productMapper.selectListNameAndProduct(productName, productId);
        List<ProductListVo> productListVos = Lists.newArrayList();
        for (Product product: products){
            ProductListVo productListVo = assembleProductListVo(product);
            productListVos.add(productListVo);
        }
        PageInfo pageResult = new PageInfo(products);
        pageResult.setList(productListVos);
        return ServiceResponse.createBySuccess(pageResult);
    }

    @Override
    public ServiceResponse<ProductDetailVo> getProductDetail(Integer productId) {
        if (productId == null){
            return ServiceResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null){
            return ServiceResponse.createByErrorMessage("产品已经下架或者删除");
        }
        if (product.getStatus() != Const.ProductStatusEnum.ON_SALE.getCode()){
            return ServiceResponse.createByErrorMessage("产品已下架或者删除");
        }
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServiceResponse.createBySuccess(productDetailVo);
    }

    @Override
    public ServiceResponse<PageInfo> getProductByKeywordCategory(String keyword, Integer categoryId, Integer pageNum, Integer pageSize, String orderBy ) {
        //参数检查
        if (StringUtils.isBlank(keyword) && categoryId == null){
            return ServiceResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<Integer> categoryList = Lists.newArrayList();
        if (categoryId != null){
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if (category == null && StringUtils.isBlank(keyword)){
                //查找不到参数,并且还没有关键字,返回空集合,不报错
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVo> productListVos = Lists.newArrayList();
                PageInfo info = new PageInfo(productListVos);
                return ServiceResponse.createBySuccess(info);
            }
            //类型id不等于空,那么就根据id来递归获取到所有的子id
            categoryList = iCategoryService.getCategoryAndDeepChildrenCategory(category.getId()).getData();
        }
        //获取到了类型id集,而关键字还不确定
        //先确定关键字的存在与否
        if (StringUtils.isNotBlank(keyword)){
            //拼接模糊查询
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
        }

        //处理好参数的转换后,开始分页查询
        PageHelper.startPage(pageNum, pageSize);
        //设置排序
        if (StringUtils.isNotBlank(orderBy)){
            if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
                String[] orderByArray = orderBy.split("_");
                PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]);
            }
        }
        List<Product> products = productMapper.selectByNameAndCategoryIds(StringUtils.isNotBlank(keyword)?keyword:null, categoryList.size() == 0?null:categoryList);
        List<ProductDetailVo> productDetailVos = Lists.newArrayList();
        for (Product product : products){
            ProductDetailVo productDetailVo = assembleProductDetailVo(product);
            productDetailVos.add(productDetailVo);
        }
        PageInfo pageInfo = new PageInfo(products);
        pageInfo.setList(productDetailVos);
        return ServiceResponse.createBySuccess(pageInfo);
    }

    /**
     * 生成View层需要的VO
     * @param product
     * @return
     */
    private ProductDetailVo assembleProductDetailVo(Product product){
        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setId(product.getId());
        productDetailVo.setSubtitle(product.getSubtitle());
        productDetailVo.setPrice(product.getPrice());
        productDetailVo.setMainImage(product.getMainImage());
        productDetailVo.setSubImage(product.getSubImages());
        productDetailVo.setCategoryId(product.getCategoryId());
        productDetailVo.setDetail(product.getDetail());
        productDetailVo.setName(product.getName());
        productDetailVo.setStatus(product.getStatus());
        productDetailVo.setStock(product.getStock());

        //imageHost--从配置文件中获取
        productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
        //parentCategoryId
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category == null){
            productDetailVo.setParentCategoryId(0);
        }else {
            productDetailVo.setParentCategoryId(category.getParentId());
        }
        //createTime
        productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        //updateTime
        productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
        return productDetailVo;
    }

    /**
     * 生成View层需要的VO
     * @param product
     * @return
     */
    private ProductListVo assembleProductListVo(Product product){
        ProductListVo productListVo = new ProductListVo();
        productListVo.setId(product.getId());
        productListVo.setName(product.getName());
        productListVo.setCategoryId(product.getCategoryId());
        productListVo.setMainImage(product.getMainImage());
        productListVo.setPrice(product.getPrice());
        productListVo.setStatus(product.getStatus());
        productListVo.setSubtitle(product.getSubtitle());
        productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
        return productListVo;
    }



}
